<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>成远生产管控平台 - 用户管理</title>
    <link rel="stylesheet" href="./layui/css/layui.css"/>
    <script src="./layui/layui.js"></script>
    <script>
        // 全局配置
        window.appConfig = {
            // apiBaseUrl: 'http://localhost:8080' // 开发环境
            apiBaseUrl: 'http://59.110.144.74:8080' // 生产环境
        };
    </script>

    <style>
        body {
            padding: 20px;
        }
    </style>
</head>
<body>

<div class="layui-container" style="padding: 20px;">
    <form class="layui-form" id="userForm" lay-filter="userForm">
        <input type="hidden" name="id" id="userId">

        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="username" id="username" required lay-verify="required|username"
                       placeholder="请输入用户名" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input type="password" name="password" id="password" lay-verify="required|password"
                       placeholder="请输入密码" class="layui-input" autocomplete="new-password">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <select name="isAdmin" id="isAdmin" lay-verify="required">
                    <option value="true">管理员</option>
                    <option value="false">普通用户</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">所属单位</label>
            <div class="layui-input-block">
                <select name="unitId" id="unitId" lay-verify="required" lay-search>
                    <!-- 单位数据由 JS 异步加载 -->
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="saveUser">保存</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                <button type="button" class="layui-btn layui-btn-danger" onclick="window.history.back()">返回</button>
            </div>
        </div>
    </form>
</div>

<script>
    layui.use(['form', 'layer', 'jquery'], function () {
        const form = layui.form;
        const layer = layui.layer;
        const $ = layui.jquery;

        let units = [];

        // 加载单位数据
        async function loadUnits() {
            try {
                const res = await $.ajax({
                    url: window.appConfig.apiBaseUrl +'/unit/all',
                    method: 'GET'
                });
                if (res.code === 200 && Array.isArray(res.data)) {
                    units = res.data;
                    const unitSelect = $('#unitId');
                    unitSelect.empty().append('<option value="">请选择单位</option>');
                    res.data.forEach(unit => {
                        unitSelect.append(`<option value="${unit.id}">${unit.unitName}</option>`);
                    });
                    form.render('select');
                } else {
                    layer.msg('单位数据加载失败', { icon: 2 });
                }
            } catch (error) {
                layer.msg('请求单位失败: ' + error.statusText, { icon: 2 });
            }
        }

        // 初始化页面数据（如果是编辑）
        const urlParams = new URLSearchParams(window.location.search);
        const mode = urlParams.get('mode');
        const userId = urlParams.get('id');
        const username = urlParams.get('username');
        const isAdmin = urlParams.get('isAdmin') === 'true';
        const unitId = urlParams.get('unitId');

        if (mode === 'edit' && userId) {
            $('#userId').val(userId);
            $('#username').val(username);
            $('#isAdmin').val(isAdmin ? 'true' : 'false');
            $('#unitId').val(unitId);
            form.render('select');
        }

        // 加载单位并初始化表单
        loadUnits().then(() => {
            if (mode === 'edit' && unitId) {
                $('#unitId').val(unitId);
                form.render('select');
            }
        });

        // 表单验证规则
        form.verify({
            username: function (value, item) {
                if (value.length < 2) return '用户名至少需要2个字符';
                if (/[^\w\u4e00-\u9fa5]/.test(value)) return '用户名只能包含字母、数字、下划线和中文';
            },
            password: function (value) {
                if (value.length < 6) return '密码至少需要6个字符';
                if (!/[A-Za-z]/.test(value) || !/[0-9]/.test(value)) return '密码需要同时包含字母和数字';
            }
        });

        // 表单提交事件
        form.on('submit(saveUser)', function (data) {
            const formData = data.field;
            const isEdit = !!formData.id;

            // 密码为空则不传（保留原密码）
            if (isEdit && !formData.password) {
                delete formData.password;
            }

            $.ajax({
                url: window.appConfig.apiBaseUrl +'/user',
                method: isEdit ? 'PUT' : 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function (res) {
                    if (res.code===0) {
                        layer.msg(isEdit ? '更新成功' : '添加成功', { icon: 1 });
                        window.location.href = 'admin.html#user';
                    } else {
                        layer.msg(res.message || '操作失败', { icon: 2 });
                    }
                },
                error: function (xhr) {
                    layer.msg('请求失败: ' + xhr.statusText, { icon: 2 });
                }
            });

            return false; // 阻止默认提交
        });
    });
</script>

</body>
</html>
